<template>
  <div class="bigbox">
     <!-- 左侧盒子树结构 -->
     <div class="leftbox">
      <div class="select">
        <span class="text">能源类型/介质</span>
        <span class="span">
          <el-select v-model="model" placeholder="请选择" size="small" @change="submit">
            <el-option
            class="option"
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </span>
      </div>
      <div style="margin-top:10px;">
        <template>
              <el-autocomplete
              class="inline-input"
              v-model="filterText"
              size="small"
              style="margin-bottom: 10px;width:100%"
              :fetch-suggestions="querySearch"
              placeholder="输入关键字进行过滤"
              :trigger-on-focus="true"
              value-key="name"
              :debounce='300'
              @select="handleSelect"
            ></el-autocomplete>
          </template>
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="id"
          accordion
          :highlight-current="true"
          :default-expanded-keys="array"
          lazy
          @node-click="handleNodeClick"
          ref="tree"
          >
          <template slot-scope="{ node, data }">
            <span :style="{ fontSize:'14px',color:'#606266'}">
              <img :src="'data:image/png;base64,' + data.iconBase64" style="  width: 16px; height: 16px; margin-right: 5px; vertical-align: bottom;"/>
              {{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="rightb">
      <div class="righttop">
        <div>
          <el-radio-group v-model="radio3" size="small">
            <el-radio-button label="2">月</el-radio-button>
            <el-radio-button label="3">年</el-radio-button>
          </el-radio-group>
          <span>
            <el-date-picker v-if="radio3=='2'" v-model="value2" type="month" value-format="yyyy-MM" placeholder="选择月" size="small"></el-date-picker>
            <el-date-picker v-else v-model="value3" type="year" value-format="yyyy" placeholder="选择年" size="small"></el-date-picker>
          </span>
        </div>
        <div>
          <el-input v-model="tongbi" placeholder="请输入同比" size="small" style="width: 48%;"><span slot="suffix">同比(%)</span></el-input>
          <el-input v-model="huanbi" placeholder="请输入环比" size="small" style="width: 48%;margin-left: 10px;"><span slot="suffix">环比(%)</span> </el-input>
        </div>
        <div>
          <el-button size="small" @click="chongzhi">重 置</el-button>
          <el-button size="small" type="primary" @click="submit">查 询</el-button>
        </div>
      </div>
      <div class="rightbodyer">
        <div class="bordertitle">
          <span>同环比分析</span>
          <el-button size="small" type="primary" @click="daochu">导 出</el-button>
        </div>
        <div class="tabandech" ref="nenghaobi" style="margin-bottom: 10px;"></div>
        <div class="tabletitle">同环比报表</div>
        <div class="tabandech">
          <TableColumn :tableData="tableData" ref="tabledata"
            :tableConfig="tableConfig">
            <el-table-column
            prop="address"
            label="同比(%)"
            align="center">
            <template #default="{row}">
              <span :style="{color:row.tbRatio>tongbi?'red':'#13ce66'}">{{ row.tbRatio }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="环比(%)"
            align="center">
            <template #default="{row}">
              <span :style="{color:row.hbRatio>huanbi?'red':'#13ce66'}">{{ row.hbRatio }}</span>
            </template>
          </el-table-column>
          </TableColumn>
              <!-- 底部分页 -->
             <div class="fenye">
              <el-pagination
                background
                 layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="10"
                @current-change="gettablelist"
               :total="+totalCount">
             </el-pagination>
            </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getnengyuantypeapi} from '@/api/energy-consumption/Basic-information/gateway'
import * as echarts from 'echarts';
import {getgenjiedianapi,getzijidianapi} from '@/api/energy-consumption/Basic-information/gateway'
import { getKeywordListApi } from '@/api/Ledger3'
import TableColumn from '@/components/Table/index.vue'
import { gettongbarechapi, gettablelistapi } from '@/api/energy-consumption/Basic-analysis/EnergyCosts'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components:{TableColumn},
  data() {
    return {
      huanbi: '25',
      tongbi:'25',
      isshow:'echart',
      value3:'',
      value2:'',
      radio3:'2',
      filterText: '',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      array: [],
      options: [],
      model: '',
      tableData:[],
      tableConfig: [],
      treevalue: {},
      pageobj: {
        pageNo: 0,
        pageSize:10
      },
      totalCount: '',
      companyName:''
    };
  },

  async mounted() {
    this.gettime()
    // 获取能源介质
    const jiezhi = await getnengyuantypeapi()
    this.options = jiezhi.data.list
    this.model=jiezhi.data.list[0].code
    this.getnenghaoech([])
  },

  methods: {
       // 树节点选中
   handleNodeClick(val) {
      this.treevalue = val
      this.submit() 
    },
    // 查询
    async submit() {
      if(!this.treevalue.id) return this.$message.warning('请先选择设备')
      const {data:{list}}=await gettongbarechapi({classId:this.treevalue.id,dateString:this.radio3=='2'?this.value2:this.value3,dateType:this.radio3,energyType:this.model})
      this.getnenghaoech(list)
      this.gettablelist()
    },
    // 获取表格数据
    async gettablelist() {
      this.$refs.tabledata.loading=true
       const { data: { list, totalCount } } = await gettablelistapi({
         classId: this.treevalue.id, dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3, energyType: this.model,
         pageNo: this.pageobj.pageNo - 1, pageSize: this.pageobj.pageSize,companyName:this.companyName,name:this.treevalue.name
       })
       const unit=this.options.find(ele=>ele.code==this.model).unit
       this.tableConfig=[
        { label: '序号', type: 'index', center: 'center', width: '70' },
        { label: '单位', prop: 'companyName' },
        { label: '设备', prop: 'unitName', },
        { label: '时间', prop: 'dateTime', center: 'center' },
        { label: `本期能耗(${unit})`, prop: 'usageValue', },
        { label: `同比能耗(${unit})`, prop: 'tbValue', },
        { label: `环比能耗(${unit})`, prop: 'hbValue', },
      ]
       this.tableData=list
      this.totalCount = totalCount
      this.$refs.tabledata.loading=false
    },
    // 导出
    daochu() {
      exportexcel('ecm-microservice-biz/ecm/basic/statistics/comparison/exportExcel',{
         classId: this.treevalue.id, dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3, energyType: this.model,
         pageNo: this.pageobj.pageNo - 1, pageSize: this.pageobj.pageSize,companyName:this.companyName,name:this.treevalue.name
       },'能耗同环比')
    },
   // 树节点搜索
   async querySearch (queryString, cb) {
       setTimeout(async () => {
        const res = await getKeywordListApi({name:queryString})
      const restaurants = res.data.list
      cb(restaurants)
      },500)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      const newarr=item.pathId.split(',')
      for (let i = 0;i<newarr.length;i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      function getgaoliang(that) {
        let node = that.$refs.tree.getNode(item);
        if (node) {
          that.handleNodeClick(node.data)
          that.$refs.tree.setCurrentKey(String(item.id));
        } else {
          setTimeout(() => {
            getgaoliang(that)
          }, 500);
        }
        }
      getgaoliang(this)
    },
    // 树结构懒加载
    async loadNode (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) {
        this.companyName = ress.data.list[0].name
        this.handleNodeClick(ress.data.list[0])
        return resolve(ress.data.list)
      } else if (node.level >= 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 获取能耗同环比图表
    getnenghaoech(list) {
      var chartDom = this.$refs.nenghaobi
      var myChart = echarts.init(chartDom);
      var option;
      const timePoints=list[0]?.datalist.map(ele=>ele.timeReading)
      const series= list.map(ele => {
        return {
            name:ele.name,
            data: ele.datalist.map(ele=>ele.valueReading),
            type: 'bar',
        }
      })
      option = {
        grid: {
        top: '10%',
        bottom: '7%',
        left: '5%',
        right: '0%',
          },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          right:'center',
        },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:this.options.find(ele=>ele.code==this.model).unit
          },
        ],
        series: series
      };
      myChart.clear();
      option && myChart.setOption(option);
    },
   // 获取当前时间戳
   gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month =mon<10?'0'+mon:mon
      this.value3 = year.toString()
      this.value2 = year + '-' + month
    },
    chongzhi() {
      this.radio3='2'
      this.gettime()
      this.submit() 
    }
  },
  watch: {
    filterText (newValue) {
      this.filterText = newValue.replace(/^\[(.*?)\]/, '').replace(/\((.*?)\)$/, '')
    },
  }
};
</script>

<style scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox{
    width: 300px;
    padding: 15px;
    background-color: #fff;
    height: 100%;
    margin-right: 10px;
    .select{
      display: flex;
      align-items: center;
      .text{
        font-size: 14px;
        margin-right: 5px;
      }
      .span{
        display: inline-block;
        flex:1;
      }
    }
  }
  .rightb{
    width: calc(100% - 310px);
    height: 100%;
    .righttop{
      height: 80px;
      line-height: 80px;
      padding:  0 20px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      span{
        margin-left: 20px;
      }
    }
    .rightbodyer{
        height: calc(100% - 90px);
        padding: 20px;
        background-color: #fff;
        .bordertitle{
          display: flex;
          justify-content: space-between;
        }
        .tabletitle{
          margin-bottom: 10px;
        }
        .tabandech{
          height: 43%;
          .fenye{
            text-align: right;
            margin-top: 10px;
          }
        }
      }
  }
}
::v-deep .el-input__suffix-inner{
  color: #000;
}
</style>